package com.telecom.common;

import com.alibaba.fastjson.JSONObject;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.hutool.json.JSONUtil;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.http.IClient;
import com.dahuatech.icc.oauth.model.v202010.GeneralRequest;
import com.dahuatech.icc.oauth.model.v202010.GeneralResponse;
import org.springframework.util.ObjectUtils;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

public class HttpsUtils {

    public static GeneralResponse iRequest(String url, Method method, Map<String,Object> body) throws ClientException {

        IClient iClient = new DefaultClient();
        /**
         * 1、请求地址是统一网关入口，以 /evo-apigw 开头
         * 2、方法参见 @see com.dahuatech.hutool.http.Method
         */
        GeneralRequest generalRequest = null;
        if (Method.POST.equals(method))
        {
            String jsonString = JSONUtil.toJsonStr(body);
            System.out.println(jsonString);
            generalRequest = new GeneralRequest(url, method);
            if (!ObjectUtils.isEmpty(body))
            {
                generalRequest.body(jsonString);
            }
        }
        else
        {
            generalRequest = new GeneralRequest(url,method);
            if (!ObjectUtils.isEmpty(body))
            {
//                String jsonString = JSONUtil.toJsonStr(body);
//                generalRequest.body(jsonString);
               for (String key:body.keySet())
               {
                   generalRequest.form(key,generalRequest.get(key));
               }
            }
        }

//        generalRequest.header("Content-Type","application/json");

        // set http post body
//        if (method.equals(Method.GET)){
//            if (!ObjectUtils.isEmpty(body))
//            {
//                body.keySet().stream().forEach(key->generalRequest.form(key,body.get(key)));
//            }
//        }
//        if (method.equals(Method.POST))
//        {
//            System.out.println("post......");
//            if (!ObjectUtils.isEmpty(body))
//            {
//                String jsonString = JSONObject.toJSONString(body);
//                generalRequest.body(jsonString);
//            }
//        }
//        generalRequest.body("json请求体");
        // set http get method param 例如?name=xiao&mobile=1xxx
//        generalRequest.form("key", "value");
        // set header
//        generalRequest.header("key", "value");
        // 发起请求处理应答
        GeneralResponse generalResponse =iClient.doAction(generalRequest, generalRequest.getResponseClass());
        System.out.println("generalResponse = " + generalResponse);
        return generalResponse;
    }
}
